package gdufs.lkl.calculator;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView tvExpression;
    private TextView tvResult;
    private CalculationEngine calculationEngine;
    private CalculationHistory calculationHistory;
    private SettingsManager settingsManager;

    private StringBuilder currentInput = new StringBuilder();
    private String expression = "";
    private boolean lastInputWasOperator = false;
    private boolean lastInputWasEquals = false;
    private boolean isInErrorState = false;

    private static final int REQUEST_CODE_HISTORY = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);        // 设置工具栏
        setSupportActionBar(findViewById(R.id.toolbar));        // 初始化UI元素
        tvExpression = findViewById(R.id.tvExpression);
        tvResult = findViewById(R.id.tvResult);

        // 初始化设置管理器
        settingsManager = SettingsManager.getInstance(this);

        // 初始化计算引擎
        calculationEngine = CalculationEngine.getInstance();

        // 初始化历史记录管理器
        calculationHistory = CalculationHistory.getInstance(this);

        // 处理从历史记录传来的数据
        handleIntentData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_switch_to_calculator) {
            // 已经在计算器界面，无需操作
            return true;
        } else if (id == R.id.action_switch_to_converter) {
            switchToConverterMode();
            return true;
        } else if (id == R.id.action_switch_to_scientific) {
            switchToScientificMode();
            return true;
        } else if (id == R.id.action_history) {
            showHistory();
            return true;
        } else if (id == R.id.action_settings) {
            showSettings();
            return true;
        } else if (id == R.id.action_custom_function) {
            switchToCustomFunctionMode();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    // 按钮点击事件处理
    public void onButtonClick(View view) {
        Button button = (Button) view;
        String buttonText = button.getText().toString();

        switch (buttonText) {
            case "C":
                clearAll();
                break;
            case "CE":
                clearEntry();
                break;
            case "⌫":
                backspace();
                break;
            case "+/-":
                changeSign();
                break;
            case "=":
                calculateResult();
                break;
            case "+":
            case "-":
            case "×":
            case "÷":
                handleOperator(buttonText);
                break;
            default: // 数字和小数点
                handleNumberOrDecimal(buttonText);
        }
    }

    // 处理数字和小数点输入
    private void handleNumberOrDecimal(String input) {
        // 如果处于错误状态，清除错误并重新开始
        if (isInErrorState) {
            clearAll();
            isInErrorState = false;
        }

        if (lastInputWasEquals) {
            clearAll();
        }

        if (input.equals(".")) {
            // 避免多个小数点
            if (currentInput.toString().contains(".")) {
                return;
            }
            // 如果当前输入为空，添加前导0
            if (currentInput.length() == 0) {
                currentInput.append("0");
            }
        }

        currentInput.append(input);
        lastInputWasOperator = false;
        updateDisplay();
    }

    // 处理运算符输入
    private void handleOperator(String operator) {
        // 如果处于错误状态，清除错误并重新开始
        if (isInErrorState) {
            clearAll();
            isInErrorState = false;
            return;
        }

        if (currentInput.length() > 0) {
            expression += currentInput.toString();
            currentInput.setLength(0);
        }

        // 避免连续输入运算符
        if (lastInputWasOperator) {
            expression = expression.substring(0, expression.length() - 1);
        }
        expression += operator;
        lastInputWasOperator = true;
        lastInputWasEquals = false;
        updateDisplay();
    }

    // 计算结果
    private void calculateResult() {
        if (expression.isEmpty() && currentInput.length() == 0) {
            return;
        }
        String fullExpression = expression;
        if (currentInput.length() > 0) {
            fullExpression += currentInput.toString();
        }

        try {
            // 使用计算引擎计算表达式
            double result = calculationEngine.evaluateExpression(fullExpression);            // 格式化结果显示（使用设置中的小数位数）
            String resultStr = calculationEngine.formatResult(result, settingsManager.getDecimalPlaces());// 显示结果
            tvResult.setText(resultStr);

            // 保存到历史记录
            calculationHistory.addHistory(fullExpression, resultStr, "basic");

            // 显示计算过程
            tvExpression.setText(fullExpression + " = " + resultStr);

            // 重置状态
            expression = "";
            currentInput.setLength(0);
            currentInput.append(resultStr);
            lastInputWasEquals = true;
            isInErrorState = false;
        } catch (Exception e) {
            tvResult.setText("错误");
            isInErrorState = true;
        }
    }

    // 清除所有输入
    private void clearAll() {
        currentInput.setLength(0);
        expression = "";
        lastInputWasOperator = false;
        lastInputWasEquals = false;
        isInErrorState = false;
        updateDisplay();
    }

    // 清除当前输入
    private void clearEntry() {
        if (isInErrorState) {
            clearAll();
            return;
        }
        currentInput.setLength(0);
        updateDisplay();
    }

    // 退格操作
    private void backspace() {
        if (isInErrorState) {
            clearAll();
            return;
        }
        if (currentInput.length() > 0) {
            currentInput.deleteCharAt(currentInput.length() - 1);
            updateDisplay();
        }
    }

    // 切换数值符号
    private void changeSign() {
        if (isInErrorState) {
            clearAll();
            return;
        }
        if (currentInput.length() > 0) {
            if (currentInput.charAt(0) == '-') {
                currentInput.deleteCharAt(0);
            } else {
                currentInput.insert(0, '-');
            }
            updateDisplay();
        }
    }

    // 更新显示内容
    private void updateDisplay() {
        tvResult.setText(currentInput.length() > 0 ? currentInput.toString() : "0");
        tvExpression.setText(expression);
    }

    // 切换到科学计算器模式
    private void switchToScientificMode() {
        Intent intent = new Intent(this, ScientificCalculatorActivity.class);
        startActivity(intent);
    }

    // 切换到换算器模式
    private void switchToConverterMode() {
        Intent intent = new Intent(this, ConverterActivity.class);
        startActivity(intent);
    }

    // 切换到换算器模式
    private void switchToCustomFunctionMode() {
        Intent intent = new Intent(this, CustomFunctionManagerActivity.class);
        startActivity(intent);
    }

    // 显示历史记录
    private void showHistory() {
        Intent intent = new Intent(this, HistoryActivity.class);
        startActivity(intent);
    }

    // 显示设置
    private void showSettings() {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }

    /**
     * 处理从历史记录传来的Intent数据
     */
    private void handleIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            String selectedExpression = intent.getStringExtra(HistoryActivity.EXTRA_SELECTED_EXPRESSION);
            String selectedResult = intent.getStringExtra(HistoryActivity.EXTRA_SELECTED_RESULT);

            if (selectedExpression != null) {
                // 复用表达式
                clearAll();
                expression = selectedExpression;
                updateDisplay();
            } else if (selectedResult != null) {
                // 复用结果
                clearAll();
                currentInput.append(selectedResult);
                updateDisplay();
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntentData();
    }
}